import express from 'express'
import cors from 'cors';
import bodyParser from 'body-parser';
import jwt from 'jsonwebtoken';
import crypto from 'crypto';

const app = express();
const PORT = 8080;

// 中间件
app.use(cors());
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));

// 模拟数据库
let products = [
  { id: 1, name: '商品1', price: 100, description: '这是商品1', count: 1, pic: "https://gw.alipayobjects.com/zos/antfincdn/LlvErxo8H9/photo-1503185912284-5271ff81b9a8.webp" },
  { id: 2, name: '商品2', price: 200, description: '这是商品2', count: 2, pic: "https://zos.alipayobjects.com/rmsportal/jkjgkEfvpUPVyRjUImniVslZfWPnJuuZ.png" }
];

let users = [];

// 工具函数
const generateToken = (user) => {
  return jwt.sign({ id: user.id, username: user.username }, 'your-secret-key', { expiresIn: '1h' });
};

const verifyToken = (req, res, next) => {
  const token = req.headers['authorization'];

  if (!token) return res.status(403).json({ message: 'No token provided' });

  jwt.verify(token.replace('Bearer ', ''), 'your-secret-key', (err, decoded) => {
    if (err) return res.status(401).json({ message: 'Unauthorized' });
    req.user = decoded;
    next();
  });
};

const noVerifyToken = (req, res, next) => next()

// 用户注册
app.post('/my/regUser', (req, res) => {
  const { username, password } = req.body;

  if (users.find(u => u.username === username)) {
    return res.status(400).json({ message: '用户名已存在' });
  }

  const hashedPassword = crypto.createHash('sha256').update(password).digest('hex');
  const newUser = { id: Date.now(), username, password: hashedPassword };

  users.push(newUser);
  res.status(200).json({ message: '注册成功' });
});

// 用户登录
app.post('/my/login', (req, res) => {
  const { username, password } = req.body;
  const hashedPassword = crypto.createHash('sha256').update(password).digest('hex');

  const user = users.find(u => u.username === username && u.password === hashedPassword);

  if (!user) {
    return res.status(401).json({ message: '认证失败' });
  }

  const token = generateToken(user);
  res.json({ token });
});

// 获取商品列表
app.get('/api/mall', noVerifyToken, (req, res) => {
  res.json(products);
});

// 新增商品
app.post('/api/addMall', noVerifyToken, (req, res) => {
  console.log('req.body :>> ', req.body);
  const index = products.findIndex(p => p.id == req.body.id);
  console.log('index :>> ', index);

  if (index !== -1) {
    return res.status(404).json({ message: '商品已存在' });
  }

  const newProduct = {
    id: Date.now(),
    ...req.body
  };

  products.push(newProduct);
  res.status(200).json(newProduct);
});

// 修改商品
app.post('/api/editMall', noVerifyToken, (req, res) => {
  console.log('editMall req.body :>> ', req.body);
  const { id, ...updateData } = req.body;
  const index = products.findIndex(p => p.id == id);

  if (index === -1) {
    return res.status(404).json({ message: '商品不存在' });
  }

  products[index] = { ...products[index], ...updateData };
  res.json(products[index]);
});

// 删除商品
app.delete('/api/deleteMall/:id', noVerifyToken, (req, res) => {
  const id = parseInt(req.params.id);
  const index = products.findIndex(p => p.id === id);

  if (index === -1) {
    return res.status(404).json({ message: '商品不存在' });
  }

  products.splice(index, 1);
  res.json({ message: '删除成功' });
});

// 根据名称查询商品
app.post('/api/getMallByName', verifyToken, (req, res) => {
  const { name } = req.body;
  const result = products.filter(p => p.name.includes(name));
  res.json(result);
});

// 启动服务器
app.listen(PORT, () => {
  console.log(`Server running on port ${PORT}`);
});
